// ignore_for_file: library_private_types_in_public_api

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:device_screen_recorder/device_screen_recorder.dart';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ScreenRecorderAndAudioPage(),
    );
  }
}

class ScreenRecorderAndAudioPage extends StatefulWidget {
  const ScreenRecorderAndAudioPage({super.key});

  @override
  _ScreenRecorderAndAudioPageState createState() =>
      _ScreenRecorderAndAudioPageState();
}

class _ScreenRecorderAndAudioPageState
    extends State<ScreenRecorderAndAudioPage> {
  /// 设备存储路径
  String directory = '';

  /// 未压缩的录屏地址
  /// 未压缩的地址是无用的 防止需要原文件，留此参数
  String _videoFilePath = '';

  /// 压缩后的录屏地址
  String _videoYSFilePath = '';

  /// 是否已经开始录屏
  /// 防止多次点击，过滤一下
  bool isBegin = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      directory = (await getApplicationDocumentsDirectory()).path;
    });
  }

  Future<void> startRecording() async {
    if (!isBegin) {
      await _checkPermissionStatus();

      /// 这时候就已经确定了地址文件名
      /// 用DataTime.now()是为了保证文件名的唯一性
      startRecord(videoName: "screenRecord${DateTime.now().toString()}");
      _videoYSFilePath =
          "$directory/screenRecordYS${DateTime.now().toString()}.mp4";
      isBegin = true;
    }
  }

  Future<void> stopRecording() async {
    if (isBegin) {
      isBegin = false;

      /// 停止录屏
      _videoFilePath = await stopRecord() ?? '';

      /// 压缩视频
      await _compressVideo('1M');

      /// 将压缩后的视频保存图库
      await ImageGallerySaver.saveFile(_videoYSFilePath);

      /// 上传服务器
      _upLoad();
    }
  }

  /// 检查权限
  Future<void> _checkPermissionStatus() async {
    await Permission.microphone.status;
    await Permission.microphone.request();
    await Permission.storage.status;
    await Permission.storage.request();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Screen Recorder and Audio Recorder'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: startRecording,
              child: const Text('Start Recording'),
            ),
            ElevatedButton(
              onPressed: stopRecording,
              child: const Text('Stop Recording'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  /// 开始录屏
  Future<void> startRecord({required String videoName}) async {
    await DeviceScreenRecorder.startRecordScreen(
        name: videoName, recordAudio: true);
  }

  /// 结束录屏
  Future<String?> stopRecord() async {
    return await DeviceScreenRecorder.stopRecordScreen();
  }

  /// 压缩图片
  Future<void> _compressVideo(String btype) async {
    /// 通过传入比特率就可调控压缩
    final arguments = ['-i', _videoFilePath, '-b:v', btype, _videoYSFilePath];
    await FFmpegKit.executeWithArguments(arguments);
  }

  /// 上传方法
  Future<void> _upLoad() async {
    final compressedVideoFile = File(_videoYSFilePath);
    const url = 'YOUR_SERVER_URL_HERE';
    final response = await http.post(
      Uri.parse(url),
      body: {'video': base64Encode(compressedVideoFile.readAsBytesSync())},
    );

    if (response.statusCode == 200) {
    } else {}
  }
}
